<!-- 商家会员的批量操作 -->
<template>
  <div class="batch-send-merchant-member">
    <el-steps :active="active" finish-status="success">
      <el-step title="选择门店"></el-step>
      <el-step title="赠送填写"></el-step>
    </el-steps>

    <div v-show="active == 0">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="search()">
        <el-form-item label="店铺名称">
          <br /><br />
          <el-input v-model="formInline.storeName" clearable style="margin-left: -70px; width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="店铺状态" style="margin-left:15px">
          <br /><br />
          <el-select v-model="formInline.status" clearable style="margin-left: -80px; width: 200px">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="停用" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="大区名称" style="margin-left:15px">
          <br /><br />
          <el-select v-model="formInline.zqName" clearable filterable @change="selCore(formInline.zqName)"
            style="margin-left: -80px; width: 200px">
            <el-option v-for="item in corpList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="营销区域" style="margin-left: 15px">
          <br /><br />
          <el-select v-model="formInline.jdName" clearable filterable @change="selbase(formInline.jdName)"
            style="margin-left: -80px; width: 200px">
            <el-option v-for="item in RentalPayWay" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单客户编号">
          <br /><br />
          <el-input v-model="formInline.orderCustomerCode" clearable style="margin-left: -95px; width: 200px"></el-input>
        </el-form-item>

        <!-- <el-form-item label="上岗日期">
          <br /><br />
          <el-date-picker v-model="formInline.dateRange" type="daterange" align="right" unlink-panels
            range-separator="至" style="margin-left: -80px; width: 410px" start-placeholder="上岗开始日期"
            end-placeholder="上岗结束日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item> -->

        <el-form-item style="margin-top:45px; text-align:right;">
          <el-button type="primary" @click="search()" size="mini" icon="el-icon-search">查询</el-button>
          <el-button type="primary" @click="kong()" size="mini" icon="el-icon-delete">清空</el-button>
        </el-form-item>
      </el-form>

      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%;" border height="500px"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }" v-loading="loading"
          @selection-change="handleSelectionChange" ref="multipleTableRef" row-key="orgSeq">
          <el-table-column type="selection" width="55" align="center" header-align="center" fixed="left" />
          <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
          <el-table-column prop="storeName" label="店铺名称" align="center"></el-table-column>
          <el-table-column prop="authCode" label="店铺授权码" align="center"></el-table-column>
          <el-table-column prop="zqName" label="所属大区" align="center"></el-table-column>
          <el-table-column prop="orderCustomerCode" label="订单客户编号" align="center"></el-table-column>
          <el-table-column prop="jdName" label="所属营销区域" align="center"></el-table-column>
          <el-table-column prop="merchantIntegral" label="普通云币" align="center"></el-table-column>
          <el-table-column prop="merchantDirectedIntegral" label="定向云币" align="center"></el-table-column>

          <el-table-column label="状态" align="center" width="80">
            <template slot-scope="scope">
              {{ scope.row.status === 0 ? '停用' : '启用' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="block" style="margin-top: 10px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 100, 300]" :current-page="listQuery.current" :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>

    <div style="width: 600px" v-show="active == 1">
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="80px">
        <el-form-item label="赠送数量" prop="number">
          <el-input-number v-model="ruleForm.number" :min="0" :step="1" step-strictly style="width: 100%" />
        </el-form-item>
        <el-form-item label="云币类型" prop="isDirectedExchange">
          <el-radio-group v-model="ruleForm.isDirectedExchange">
            <el-radio :label="0">普通云币</el-radio>
            <el-radio :label="1">定向云币</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="赠送原因" prop="cause">
          <el-input type="textarea" v-model="ruleForm.cause" :autosize="{ minRows: 2 }" />
        </el-form-item>
      </el-form>
    </div>

    <div class="batch-send-merchant-member__operate">
      <el-button @click="$router.go(-1)" size="mini" type="primary">返回</el-button>
      <el-button v-if="active == 1" @click="operateHandle(0)" size="mini">上一步</el-button>
      <el-button v-if="active == 0" type="primary" @click="operateHandle(1)" size="mini">下一步</el-button>
      <el-button v-if="active == 1" type="primary" @click="operateHandle()" :loading="btnLoading"
        size="mini">确定发放</el-button>
    </div>
  </div>
</template>

<script>
import { queryStoreUserInfo, batchAddIntegral } from '@/api/shopMemberset';
import { getAllZone, getAllBase } from '@/api/addShopapply.js';
export default {
  data() {
    return {
      active: 0,
      formInline: {
        realName: '',
        tel: '',
        storeName: '',
        status: '',
        zqName: '',
        jdName: '',
        dateRange: [],
        orderCustomerCode: ''
      },

      loading: false,
      total: 0,
      tableData: [],
      listQuery: {
        current: 1,
        size: 10,
      },
      orgSeq: '', // 门店组织机构编码
      logininfo: null, // 登录信息

      corpList: [], // 大区列表
      RentalPayWay: [], //营销区域列表

      ruleForm: {
        // memberId: '',
        // orgSeq: '',
        number: '',
        cause: '',
        // 类型：0会员赠送云币 / 1商家赠送酒币
        type: 1,
        isDirectedExchange: 0,
      },
      rules: {
        number: [
          { type: 'number', required: true, message: '请输入赠送数量', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('赠送数量不能小于0'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        isDirectedExchange: [{ required: true, message: '请选择云币类型', trigger: 'change' }],
        cause: [{ required: true, message: '请输入赠送原因', trigger: 'blur' }],
      },

      checkeds: [],
      btnLoading: false
    };
  },

  created() {
    this.logininfo = localStorage.getItem('logininfo');
    this.orgSeq = JSON.parse(this.logininfo).orgSeq;
    this.selCore(this.orgSeq);
    this._getAllZone();
    this.search();
  },

  methods: {
    search() {
      this.listQuery.current = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getList();
    },
    getList() {
      this.loading = true;
      const data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          ...this.formInline,
          onboardDateStart: this.formInline.dateRange !== null &&
            this.formInline.dateRange.length > 0
            ? this.formInline.dateRange[0]
            : '',
          onboardDateEnd: this.formInline.dateRange !== null &&
            this.formInline.dateRange.length > 1
            ? this.formInline.dateRange[1]
            : '',
          orgSeq: this.orgSeq,
          userType: 5,
        },
      };
      queryStoreUserInfo(data).then((res) => {
        this.total = res.total;
        this.tableData = res.records;

        if (this.tableData.length > 0) {
          this.$nextTick(() => {
            this.restoreSelection();
            // this.checkeds.forEach(item => {
            //   const curItem = this.tableData.find(o => o.orgSeq === item.orgSeq);
            //   this.$refs.multipleTableRef.toggleRowSelection(curItem, true)
            // })
          })
        }
      }).finally(() => {
        this.loading = false
      });
    },

    restoreSelection() {
      const table = this.$refs.multipleTableRef;
      if (!table || !this.tableData.length) return;

      // 延迟执行，确保 el-table 已经渲染完成
      this.$nextTick(() => {
        // 清空当前页之前的勾选状态（避免残留）
        table.clearSelection();

        // 遍历当前页数据，如果存在于 checkeds 中则勾选
        this.tableData.forEach(row => {
          const exists = this.checkeds.find(item => item.orgSeq === row.orgSeq);
          if (exists) {
            table.toggleRowSelection(row, true);
          }
        });
      });
    },
    selCore(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
        let data = {
          code: value,
        };
        getAllBase(data).then((res) => {
          this.RentalPayWay = res.result;
          this.formInline.jdName = '';
        });
      } else if (this.formInline.jdName != '') {
        this.orgSeq = this.formInline.jdName;
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },
    selbase(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
      } else if (this.formInline.zqName != '') {
        this.orgSeq = this.formInline.zqName;
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },

    _getAllZone() {
      let data = {};
      getAllZone(data).then((res) => {
        this.corpList = res.result;
      });
    },

    kong() {
      this.formInline = this.$options.data().formInline;
      this.orgSeq = JSON.parse(this.logininfo).orgSeq;
    },

    handleSelectionChange(val) {
      this.$nextTick(() => {
        // 获取当前页所有数据的 orgSeq
        const currentPageOrgSeqs = this.tableData.map(item => item.orgSeq);

        // 先从 checkeds 中过滤掉当前页的数据
        this.checkeds = this.checkeds.filter(
          item => !currentPageOrgSeqs.includes(item.orgSeq)
        );

        // 将当前页新选中的数据加入 checkeds
        this.checkeds = [...this.checkeds, ...val];

        // 去重（保留最后加入的）
        const uniqueMap = new Map();
        this.checkeds.forEach(item => {
          uniqueMap.set(item.orgSeq, item);
        });
        this.checkeds = Array.from(uniqueMap.values());
      })
    },

    operateHandle(step) {
      if (step != undefined) {
        if (this.checkeds.length <= 0) {
          this.$message.error('请先选择赠送门店');
        } else {
          this.active = step;
        }
      } else {
        this.$refs.ruleFormRef.validate((valid) => {
          if (valid) {
            const result = this.checkeds.map((item) => {
              return {
                memberId: item.orgSeq,
                orgSeq: item.orgSeq,
                number: this.ruleForm.number,
                cause: this.ruleForm.cause,
                type: this.ruleForm.type,
                isDirectedExchange: this.ruleForm.isDirectedExchange,
              }
            });

            if (result.length > 0) {
              this.btnLoading = true
              batchAddIntegral(result).then(res => {
                if (res.code == 1) {
                  this.$message.success('赠送成功');
                  this.$router.go(-1);
                } else {
                  this.$message.error(res.message);
                }
              }).finally(() => {
                this.btnLoading = false
              })
            }
          }
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form-item .el-select {
  width: 100%;
}
</style>
<style lang="scss" scoped>
.batch-send-merchant-member {
  .block {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  &__operate {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.demo-form-inline {
  /deep/ .el-form-item__content {
    line-height: normal;
  }
}

.table-wrapper {
  // /deep/ .el-table__fixed-right .el-table__fixed-body-wrapper {
  //   height: 420px !important;
  // }

  // /deep/ .el-table__fixed .el-table__fixed-body-wrapper {
  //   height: 420px !important;
  // }
}
</style>